var geocoder;
function criarMapa(mapContainer){
    // Create the new Goole map controller using our
    // map (pass in the actual DOM object). Center it
    // above the first Geolocated IP address.
    var map = new google.maps.Map(
        mapContainer[ 0 ],{
            zoom: 12,
            center: new google.maps.LatLng(-16.69276325351097, -49.279174804687386),
            mapTypeId: google.maps.MapTypeId.HYBRID,
            streetViewControl: false,
            panControl: false,
            zoomControl: true,
            zoomControlOptions: {
                style: google.maps.ZoomControlStyle.LARGE,
                position: google.maps.ControlPosition.LEFT_CENTER
            },
            mapTypeControl:true,
            mapTypeControlOptions: {
                style: google.maps.MapTypeControlStyle.HORIZONTAL_BAR,
                position: google.maps.ControlPosition.LEFT_BOTTOM
            }
        });
    geocoder = new google.maps.Geocoder();
    return (map);
}

// I add a marker to the map using the given latitude
// and longitude location.
function addMarker(map, latitude, longitude, label, type, pic){
    var drag = false;
    // Create the marker - this will automatically place it
    // on the existing Google map (that we pass-in).
    var marker;
    switch(type){
        case 'point':
            pic = pic != null ? pic : 'img/pt-default.png';
            //pic = pic != null ? pic : 'img/gay_bonito.jpg';
            var image = new google.maps.MarkerImage(
                pic,
                new google.maps.Size(22,28),
                new google.maps.Point(0,0),
                new google.maps.Point(11,28)
                );

            var shadow = new google.maps.MarkerImage(
                'img/pt-sw.png',
                new google.maps.Size(40,28),
                new google.maps.Point(0,0),
                new google.maps.Point(11,28)
                );
            var shape = {
                coord: [21,0,21,1,21,2,21,3,21,4,21,5,21,6,21,7,21,8,21,9,21,10,
                21,11,21,12,21,13,21,14,21,15,21,16,21,17,21,18,21,19,21,20,
                21,21,21,22,15,23,14,24,13,25,12,26,11,27,10,27,9,26,8,25,7,
                24,6,23,0,22,0,21,0,20,0,19,0,18,0,17,0,16,0,15,0,14,0,13,0,
                12,0,11,0,10,0,9,0,8,0,7,0,6,0,5,0,4,0,3,0,2,0,1,0,0,21,0],
                type: 'poly'
            };
            marker = new google.maps.Marker({
                //raiseOnDrag: drag?true:false,
                icon: image,
                shadow: shadow,
                shape: shape,
                map: map,
                position: new google.maps.LatLng(
                    latitude,
                    longitude
                    ),
                title: (label || ""),
                draggable: drag
            });
            break;
        case 'outdoor':
            pic = pic != null ? pic : 'img/outdoor-default.png';
            var image = new google.maps.MarkerImage(
                pic,
                new google.maps.Size(44,55),
                new google.maps.Point(0,0),
                new google.maps.Point(22,55)
                );

            var shadow = new google.maps.MarkerImage(
                'img/outdoor-sw.png',
                new google.maps.Size(76,55),
                new google.maps.Point(0,0),
                new google.maps.Point(22,55)
                );
            var shape = {
                coord: [42,0,43,1,43,2,43,3,43,4,43,5,43,6,43,7,43,8,43,9,43,10,
                43,11,43,12,43,13,43,14,43,15,43,16,43,17,43,18,43,19,43,20,
                43,21,43,22,43,23,43,24,43,25,43,26,43,27,43,28,43,29,43,30,
                43,31,43,32,43,33,43,34,43,35,43,36,43,37,43,38,43,39,43,40,
                43,41,43,42,42,43,32,44,31,45,30,46,29,47,28,48,27,49,26,50,
                25,51,24,52,23,53,22,54,21,54,20,53,19,52,18,51,17,50,16,49,
                15,48,14,47,13,46,12,45,11,44,1,43,0,42,0,41,0,40,0,39,0,38,
                0,37,0,36,0,35,0,34,0,33,0,32,0,31,0,30,0,29,0,28,0,27,0,26,
                0,25,0,24,0,23,0,22,0,21,0,20,0,19,0,18,0,17,0,16,0,15,0,14,
                0,13,0,12,0,11,0,10,0,9,0,8,0,7,0,6,0,5,0,4,0,3,0,2,0,1,1,0,
                42,0],
                type: 'poly'
            };
            marker = new google.maps.Marker({
                //raiseOnDrag: false,
                icon: image,
                shadow: shadow,
                shape: shape,
                map: map,
                position: new google.maps.LatLng(
                    latitude,
                    longitude
                    ),
                title: (label || ""),
                draggable: drag
            });
            break;
        default:
            marker = new google.maps.Marker({
                map: map,
                position: new google.maps.LatLng(
                    latitude,
                    longitude
                    ),
                title: (label || ""),
                draggable: drag
            });           
    }
    // Return the new marker reference.
    return( marker );
}

function getMergedUrl(img1, img2, width, height){
    var frame = new Image();
    frame.src = img1;
    var pic = new Image();
    pic.src = img2;
    // Create an empty canvas element
    var canvas = document.createElement("canvas");
    canvas.width = width;
    canvas.height = height;

    // Copy the image contents to the canvas
    var ctx = canvas.getContext("2d");
    ctx.drawImage(frame, 0, 0);
    ctx.drawImage(pic, 4, 4);

    // Get the data-URL formatted image
    var dataURL = canvas.toDataURL("image/png");

    return dataURL;
}

// I update the marker's position and label.
function updateMarker( marker, latitude, longitude, label ){
    // Update the position.
    marker.setPosition(
        new google.maps.LatLng(
            latitude,
            longitude
            )
        );
    // Update the title if it was provided.
    if (label){
        marker.setTitle( label );
    }
}

function removeMarkers(markers){
    if (markers) {
        for (i in markers) {
            markers[i].setMap(null);
        }
        markers.length = 0;
    }
}

function buscarLugares(tipo, latitude, longitude, categorias, max, mapa, marcadores){
    $.post("listalocais",{
        "tipo":tipo,
        "lat":latitude,
        "lng":longitude,
        "cat":categorias,
        "max":max
    }, function(data) {
        if(data == null){
        // houve algum erro
        }else{
            var results = data.lugares.length;
            if(results <= 0){
            // nenhum resultado retornado
            }else{
                removeMarkers(marcadores);
                var lugares = data.lugares;
                for(var i=0; i < lugares.length; i++){
                    var lugar = lugares[i];
                    //setTimeout(function(){
                        adicionarLugares(lugar, mapa, marcadores);
                    //}, 200);
                }
            }
        }
    });
}

function adicionarLugares(lugar, mapa, marcadores){
    var marcador = addMarker(mapa, lugar.latitude, lugar.longitude, lugar.nome,'point');
    marcadores.push(marcador);
    var boxText = document.createElement("div");
    boxText.style.cssText = "border: 1px solid black; margin-top: 8px; background:#333; color:#FFF; font-family:Arial; font-size:12px; padding: 5px; border-radius:6px; -webkit-border-radius:6px; -moz-border-radius:6px;";
    boxText.innerHTML = lugar.nome;
    var infoOptions = {
        content: boxText,
        maxWidth: 200,
        pixelOffset: new google.maps.Size(-140, 0),
        boxStyle: {
            background: "url('http://google-maps-utility-library-v3.googlecode.com/svn/trunk/infobox/examples/tipbox.gif') no-repeat",
            opacity: 0.9,
            width: "200px"
        },
        closeBoxMargin: "12px 4px 2px 2px",
        closeBoxURL: "http://www.google.com/intl/en_us/mapfiles/close.gif",
        infoBoxClearance: new google.maps.Size(1, 1)
    };
    var infoWindow = new InfoBox(infoOptions);
    google.maps.event.addListener(marcador,'click',function(){
        toggleBounce(marcador, mapa, infoWindow);
    });
    google.maps.event.addListener(infoWindow, 'closeclick', function(){
        toggleBounce(marcador, mapa, infoWindow);
    });
    var ib = new google.maps.InfoWindow({
        content: lugar.nome,
        disableAutoPan: true,
        maxWidth: 100
    });
    google.maps.event.addListener(marcador,'mouseover',function(){
        ib.open(mapa, marcador);
    });
    google.maps.event.addListener(marcador, 'mouseout', function(){
        ib.close();
    });
}

function toggleBounce(marcador, mapa, infoWindow) {
    if (marcador.getAnimation() != null) {
        marcador.setAnimation(null);
        infoWindow.close();
    } else {
        marcador.setAnimation(google.maps.Animation.BOUNCE);
        infoWindow.open(mapa, marcador);
    }
}

function centerUserLocation(map, locationMarker){
    locationMarker.setMap(null);
    locationMarker = null;
    locationMarker = tryCenterUserLocation(map, locationMarker);
}
var tipoLocator = 2;
function tryCenterUserLocation(map, locationMarker){
    switch(tipoLocator){
        case 1:
            tipoLocator++;
            if (locationMarker == null && window['navigator'] && navigator.geolocation) {
                locationMarker = centerUserLocationGeo(map, locationMarker);
            }
            break;
        case 2:
            tipoLocator++;
            if (locationMarker == null && window['google'] && google.loader.ClientLocation) {
                locationMarker = centerUserLocationGoogle(map, locationMarker);
            }
            tipoLocator++;
    }
    return locationMarker;
}

function centerUserLocationGeo(map, locationMarker){
    if (window['navigator'] && navigator.geolocation) {
        console.log('GeoLocation');
        // This is the location marker that we will be using
        // on the map. Let's store a reference to it here so
        // that it can be updated in several places.
        //var locationMarker = null;
        // Get the location of the user's browser using the
        // native geolocation service. When we invoke this method
        // only the first callback is requied. The second
        // callback - the error handler - and the third
        // argument - our configuration options - are optional.
        navigator.geolocation.getCurrentPosition(
            function( position ){
                // Check to see if there is already a location.
                // There is a bug in FireFox where this gets
                // invoked more than once with a cahced result.
                if (locationMarker){
                    return;
                }
                // Log that this is the initial position.
                //console.log( "Initial Position Found" );
 
                // Add a marker to the map using the position.
                locationMarker = addMarker(map,
                    position.coords.latitude,
                    position.coords.longitude,
                    "Initial Position"
                    );
                map.setCenter(new google.maps.LatLng( position.coords.latitude, position.coords.longitude ) );
                console.log(locationMarker.getPosition().toUrlValue());
            },
            geoLocationErrors, // error handler
            { // options
                timeout: (5 * 1000),
                maximumAge: (1000 * 60 * 15),
                enableHighAccuracy: true
            }
            );
        if(locationMarker != null){
            // Now tha twe have asked for the position of the user,
            // let's watch the position to see if it updates. This
            // can happen if the user physically moves, of if more
            // accurate location information has been found (ex.
            // GPS vs. IP address).
            //
            // NOTE: This acts much like the native setInterval(),
            // invoking the given callback a number of times to
            // monitor the position. As such, it returns a "timer ID"
            // that can be used to later stop the monitoring.
            var positionTimer = navigator.geolocation.watchPosition(
                function( position ){
                    // Log that a newer, perhaps more accurate
                    // position has been found.
                    console.log( "Newer Position Found" );
                    // Set the new position of the existing marker.
                    updateMarker(
                        locationMarker,
                        position.coords.latitude,
                        position.coords.longitude,
                        "Updated / Accurate Position"
                        );
                }
                );
            // If the position hasn't updated within 5 minutes, stop
            // monitoring the position for changes.
            setTimeout(
                function(){
                    // Clear the position watcher.
                    navigator.geolocation.clearWatch( positionTimer );
                },
                (1000 * 60 * 5)
                );
        }
        return locationMarker;
    }else{
        return null;
    }
}

function geoLocationErrors(error){  
    switch(error.code){  
        case error.PERMISSION_DENIED:
            alert("Yo");
            break;  
        case error.POSITION_UNAVAILABLE:
            alert("could not detect current position");  
            break;  
        case error.TIMEOUT:
            alert("");  
            break;  
        default:
            alert("unknown error");  
            break;  
    }  
}

function centerUserLocationGoogle(map, locationMarker){
    if (window['google'] && google.loader.ClientLocation) {
        console.log('GoogleLocation');
        var lat = google.loader.ClientLocation.latitude;
        var lng = google.loader.ClientLocation.longitude;
        locationMarker = addMarker(map,
            lat,
            lng,
            "Initial Position"
            );
        map.setCenter(new google.maps.LatLng( lat, lng ) );
        /*com.unitedCoders.geo.ll.push({
            'name':    'google', 
            'country': google.loader.ClientLocation.country,
            'city':       google.loader.ClientLocation.city,
            'lat':        lat,
            'long':      lng
        });*/
        return locationMarker;
    }else{
        return null;
    }
}